﻿const crypto = require('crypto');
const router = require('koa-router')();
const User = require('../model/user.js');
//注册
router.post('/Reg', async (ctx) => {
  let code = 200;
  let obj;
  let reqDoc;
  if (ctx.request.body.password != ctx.request.body.checkPass) {
    code = 500;
    obj = '用户密码不一致';
  } else {
    let md5 = crypto.createHash('md5');
    const userData = new User({
      username: ctx.request.body.username,
      password: md5.update(ctx.request.body.password).digest('hex'),
      create_time: ctx.request.body.create_time
    });
    await User.find({
      'username': ctx.request.body.username
    }, function (err, doc) {
      if (err) {
        code = 500;
        obj = '数据库查询失败';
        reqDoc = doc[0];
      } else {
        reqDoc = doc[0];
      }
    })
    if (typeof reqDoc == 'object') {
      code = 500;
      obj = '用户名已存在';
    } else {
      // 保存数据
      await new Promise((resolve, reject) => {
        userData.save((err) => {
          if (err) {
            reject(err);
            code = 500;
            obj = '注册失败';

          }
          resolve();
          obj = '注册成功';
        });
      });
    }
  }
  ctx.body = {
    code: code,
    obj: obj
  };
})

//登录
router.post('/login', async (ctx) => {
  await new Promise((resolve, reject) => {
    User.find({
      'username': ctx.request.body.username
    }, function (err, doc) {
      if (err) {
        reject(err);
        ctx.body = {
          code: 500,
          obj: err
        };
      } else {
        resolve();
        if (doc.length > 0) {
          let md5 = crypto.createHash('md5');
          let password = md5.update(ctx.request.body.password).digest('hex');
          if (password == doc[0].password) {
            ctx.body = {
              code: 200,
              obj: '登录成功!'
            };
          } else {
            ctx.body = {
              code: 500,
              obj: '密码错误！'
            };
          }
        } else {
          ctx.body = {
            code: 500,
            obj: '用户不存在'
          };
        }
      }
    })
  });
})

//查询用户and图片
router.post('/getUserPic', async (ctx) => {
  await new Promise((resolve, reject) => {
    User.aggregate([{
      $lookup: {
        from: "pics", //需要去连接的collection，也就是右表的表名
        localField: "username", //需要去进行连接的左表的字段名
        foreignField: "username", //右表(from参数后的那个collection)的字段名，可以与左表的字段名(localField)不一样,但是数据类型必须一致
        as: "items" //形成的新的数组的名称，为什么叫数组呢？你看一下后面的例子就知道了
      }
    }], (err, docs) => {
      if (err) {
        reject(err);
        ctx.body = {
          code: 500,
          obj: err
        };
      }
      resolve();
      let arr = [];
      for (let i = 0; i < docs.length; i++) {
        if (docs[i].items.length > 0) {
          let items = {
            pic: docs[i].items[0].pic,
            username: docs[i].username,
            password: docs[i].password,
            create_time: docs[i].create_time,
            _id: docs[i]._id,
          }
          arr.push(items);
        }
      }
      let json = {
        list: arr,
        total: arr.length
      }
      ctx.body = {
        code: 200,
        obj: json
      };
    })
  });
})
//查询用户
router.post('/getUser', async (ctx) => {
  let pageSize = ctx.request.body.pageSize;
  let startTime = ctx.request.body.startTime;
  let endTime = ctx.request.body.endTime;
  if (!startTime) {
    startTime = '2000-01-01'
  }
  if (!endTime) {
    endTime = '2100-01-01'
  }
  let username = ctx.request.body.username;
  let page = (ctx.request.body.page - 1) * pageSize;
  let jsonPage = {
    $or: [ // 多字段同时匹配
      {
        username: {
          $regex: username
        },
        create_time: {
          $gt: new Date(`${startTime} 00:00:00`),
          $lt: new Date(`${endTime} 23:59:59`)
        }
      }
    ]
  }
  let query = User.find(jsonPage);
  let total = await query.count().exec(); //查询所有条数
  await new Promise((resolve, reject) => {
    User.aggregate([{
        $sort: {
          create_time: -1
        }
      }, {
        $match: jsonPage,
      },
      {
        $skip: page,
      }, {
        $limit: pageSize,
      }
    ], (err, docs) => {
      if (err) {
        reject(err);
        ctx.body = {
          code: 500,
          obj: err
        };
      }
      resolve();
      let json = {
        list: docs,
        total: total
      }
      ctx.body = {
        code: 200,
        obj: json
      };
    })
  });
})
//查询用户
// router.post('/getUser', async (ctx) => {
//   let pageSize = ctx.request.body.pageSize;
//   let startTime = ctx.request.body.startTime;
//   let endTime = ctx.request.body.endTime;
//   if (!startTime) {
//     startTime = '2000-01-01'
//   }
//   if (!endTime) {
//     endTime = '2100-01-01'
//   }
//   let username = ctx.request.body.username;
//   let page = (ctx.request.body.page - 1) * pageSize;
//   let _filter = {
//     $or: [ // 多字段同时匹配
//       {
//         username: {
//           $regex: username
//         },
//         create_time: {
//           $gt: new Date(`${startTime} 00:00:00`),
//           $lt: new Date(`${endTime} 23:59:59`)
//         }
//       }
//     ],
//   }
//   const query = User.find(_filter);
//   const total = await query.count().exec(); //查询所有条数
//   await new Promise((resolve, reject) => {
//     User.find(_filter, function (err, doc) {
//         if (err) {
//           reject(err);
//           ctx.body = {
//             code: 500,
//             obj: err
//           };
//         } else {
//           resolve();
//           let json = {
//             list: doc,
//             total: total
//           }
//           ctx.body = {
//             code: 200,
//             obj: json
//           };
//         }
//       }).sort({
//         create_time: -1
//       }).limit(pageSize).skip(page)
//       .exec()
//   });
// })
//删除用户
router.post('/delUser', async (ctx) => {
  await new Promise((resolve, reject) => {
    User.remove({
      'username': ctx.request.body.username
    }, function (err) {
      if (err) {
        reject(err);
        ctx.body = {
          code: 500,
          obj: err
        };
      } else {
        resolve();
        ctx.body = {
          code: 200,
          obj: "删除成功"
        };
      }
    })
  });
})

//编辑用户
router.post('/updetaUser', async (ctx) => {
  await new Promise((resolve, reject) => {
    let md5 = crypto.createHash('md5');
    let password = md5.update(ctx.request.body.password).digest('hex');
    User.update({
      '_id': ctx.request.body.id
    }, {
      $set: {
        username: ctx.request.body.username,
        password: password,
        create_time: ctx.request.body.create_time,
      }
    }, function (err) {
      if (err) {
        reject(err);
        ctx.body = {
          code: 500,
          obj: err
        };
      } else {
        resolve();
        ctx.body = {
          code: 200,
          obj: "更新成功"
        };
      }
    })
  });
})
module.exports = router.routes();
